package com.wjm.notification.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.RemoteViews;

import com.wjm.notification.R;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class UploadIntentService extends IntentService {


    public static final String ACTION = "com.wjm.notification.service.UploadIntentService";
    public static final String EXTRA_KEY = "EXTRA_KEY";
    public static final String startUpload = "startUpload";
    private static final String TAG = "UploadIntentService";

    public UploadIntentService() {
        super("UploadIntentService");
    }

    public UploadIntentService(String name) {

        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        // 根据 Intent的不同，进行不同的事务处理
        String taskName = intent.getExtras().getString(EXTRA_KEY);
        switch (taskName) {
            case startUpload://开始上传
                //开始下载，并显示上传进度notifi
                startUpload();
                testUpload();
                break;
            case "task2":
                break;
            default:
                break;
        }

    }

    private int id = 1;
    private final int start = 1;//开始上传
    private final int uploading = 2;//上传中
    private final int finish = 3;//上传完成
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            int pb = msg.arg1;

            switch (what) {
                case start:
//                    rv = new RemoteViews(getPackageName(),
//                            R.layout.my_notification);
//                    rv.setTextViewText(R.id.text_title, "正在下载中");
//                    rv.setProgressBar(R.id.progress, 100, progress, false);
//                    rv.setTextViewText(R.id.text_content, progress + "%");
//                    myNotify.contentView = rv;
//                    notificationManager.notify(0, myNotify);


                    handlerUpdateNotifiStart();

                    break;
                case uploading:

                    handlerUpdateNotifiUploading(pb);

                    break;
                case finish:
                    break;
            }


        }
    };

    private void handlerUpdateNotifiUploading(int pb) {

//        rv = new RemoteViews(getPackageName(),
//                R.layout.my_notification);
//        remoteViews.setTextViewText(R.id.tv_pb, "正在下载中");
        Log.d(TAG, "handlerUpdateNotifiUploading pb="+pb);
        if (pb > 0) {//设置按钮为暂停

        }
        if (pb > 100) {//隐藏暂停按钮,并设置通知为可消除的通知
            pb = 100;
//            Notification.FLAG_SHOW_LIGHTS              //三色灯提醒，在使用三色灯提醒时候必须加该标志符
//            Notification.FLAG_ONGOING_EVENT          //发起正在运行事件（活动中）
//            Notification.FLAG_INSISTENT   //让声音、振动无限循环，直到用户响应 （取消或者打开）
//            Notification.FLAG_ONLY_ALERT_ONCE  //发起Notification后，铃声和震动均只执行一次
//            Notification.FLAG_AUTO_CANCEL      //用户单击通知后自动消失
//            Notification.FLAG_NO_CLEAR          //只有全部清除时，Notification才会清除 ，不清楚该通知(QQ的通知无法清除，就是用的这个)
//            Notification.FLAG_FOREGROUND_SERVICE    //表示正在运行的服务

            notification.flags = Notification.FLAG_AUTO_CANCEL;// 用户单击通知后自动消失
        }
        if(pb==100){
            notification.flags = Notification.FLAG_AUTO_CANCEL;// 用户单击通知后自动消失
        }
        remoteViews.setProgressBar(R.id.pb, 100, pb, false);
        remoteViews.setTextViewText(R.id.tv_pb, pb + "%");
//        notification.contentView = rv;
        if(null!=notificationManager){
            notificationManager.notify(id, notification);
        }
        Log.d(TAG, "handlerUpdateNotifiUploading");
        if(pb==100){
            handler.removeMessages(uploading);
        }
    }

    private RemoteViews remoteViews;

    private void handlerUpdateNotifiStart() {
        notification.when = System.currentTimeMillis();
        notification.flags = Notification.FLAG_NO_CLEAR;// 不能够自动清除


        //通过RemoteViews来创建自定义的Notification视图
        remoteViews = new RemoteViews(getPackageName(), R.layout.notification);
//        //指定展开时的视图
//        notification.bigContentView = remoteViews;
        notification.contentView = remoteViews;
        remoteViews.setProgressBar(R.id.pb, 100, 0, false);
        remoteViews.setTextViewText(R.id.tv_pb, "开始下载"); //这里就是使用自定义布局了 初始化的时候不设置Intent,点击的时候就不会有反应了,亏得我还找了好久  T-T

        notificationManager.notify(id, notification);
        Log.d(TAG, "handlerUpdateNotifiStart");
    }

    private int getNextInt(int min, int max) {
//       int max=20;
//       int min=10;
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        System.out.println(s);
        return s;
    }

    private void testUpload() {
        TimerTask task = new TimerTask() {
            public void run() {
                //execute the task

                boolean flag = false;
                int pb = 0;
                while (pb < 100) {

                    Log.d(TAG, "testUpload Thread while");
//                    long millis = 1000;
                    try {

                        int millis = getNextInt(1000, 5000);
//                        Log.d(TAG, "testUpload Thread while millis=" + millis);
                        Thread.sleep(millis);
                        //1-5的随机数

                        Message message = new Message();
                        message.what = uploading;

                        pb ++;
                        Log.d(TAG, "testUpload Thread while pb=" + pb);
                        message.arg1 = pb;
                        handler.sendMessage(message);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Log.d(TAG, "testUpload Thread while end 上传完成");

            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 3000);
/*

        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean flag = false;
                int pb = 0;
                while (pb < 100) {

                    Log.d(TAG, "testUpload Thread while");
                    long millis = 500;
                    try {

                        Thread.sleep(millis);
                        //1-5的随机数
                        int testPb = getNextInt(1, 5);
                        Message message = new Message();
                        message.what = uploading;
                        Log.d(TAG, "testUpload Thread while testPb=" + testPb);
                        pb += testPb;
                        Log.d(TAG, "testUpload Thread while pb=" + pb);
                        message.arg1 = pb;
                        handler.sendMessage(message);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Log.d(TAG, "testUpload Thread while end 上传完成");
            }
        }).start();*/
    }


    /**
     * 开始上传
     */
    private void startUpload() {
        initUploadNotifi();
    }

    private NotificationManager notificationManager;
    private Notification notification = null;

    /**
     * 初始上传进度notifi
     */
    private void initUploadNotifi() {
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(""));
        int requestCode = 0;
        int flags = 0;
        PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, flags);
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setAutoCancel(true);
        builder.setContentTitle("标题视频上传中...");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//sdk>=21(5.0) 设置通知级别
            builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        }
        builder.setContentText("内容视频上传中...");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {//sdk>=16(4.1) 才有的通知构建方式
            notification = builder.build();
        }

        updateNotifiStart();

    }

    private void updateNotifiStart() {
        Message message = new Message();
        message.what = start;
        handler.sendMessage(message);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestory");
        notification = null;
        notificationManager = null;
    }

}
